package com.kmxd.ams.app.system;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kmxd.ams.client.system.ISysUserConfigSvc;
import com.kmxd.ams.client.system.dto.SysUserConfigAddDTO;
import com.kmxd.ams.client.system.dto.SysUserConfigQueryDTO;
import com.kmxd.ams.client.system.vo.SysUserConfigListVO;
import com.kmxd.ams.core.common.query.QueryGen;
import com.kmxd.ams.core.util.ConvertUtil;
import com.kmxd.ams.infra.system.entity.SysUserConfig;
import com.kmxd.ams.infra.system.mapper.SysUserConfigMapper;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户配置表 服务实现类
 *
 * @author nickbi
 * @since 2022-07-16
 */
@Service
@AllArgsConstructor
public class SysUserConfigSvcImpl extends ServiceImpl<SysUserConfigMapper, SysUserConfig>
    implements ISysUserConfigSvc {

  private SysUserConfigMapper sysUserConfigMapper;

  @Override
  public List<SysUserConfigListVO> selectList(SysUserConfigQueryDTO req) {
    LambdaQueryWrapper<SysUserConfig> queryWrapper =
        QueryGen.init(new QueryWrapper<SysUserConfig>(), req).lambda();
    List<SysUserConfig> list = sysUserConfigMapper.selectList(queryWrapper);
    return BeanUtil.copyToList(list, SysUserConfigListVO.class);
  }

  @Override
  public void change(SysUserConfigAddDTO req) {
    SysUserConfig sysUserConfig =
        sysUserConfigMapper.selectOne(
            Wrappers.<SysUserConfig>lambdaQuery()
                .eq(SysUserConfig::getUserId, req.getUserId())
                .eq(SysUserConfig::getCode, req.getCode()));
    if (null == sysUserConfig) {
      sysUserConfigMapper.insert(ConvertUtil.toBean(req, SysUserConfig.class));
      return;
    }
    if (req.getContent().equals(sysUserConfig.getContent())) {
      return;
    }
    sysUserConfigMapper.update(
        null,
        Wrappers.<SysUserConfig>lambdaUpdate()
            .eq(SysUserConfig::getUserId, req.getUserId())
            .eq(SysUserConfig::getCode, req.getCode())
            .set(SysUserConfig::getContent, req.getContent()));
  }
}
